<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 楼层信息
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-input
              v-model="query.region"
              placeholder="校区名"
              class="handle-input mr10"
          ></el-input>
          <el-form-item label="楼栋">
            <el-select
                v-model="query.name"
                filterable
                placeholder="请选择楼栋名"
                @focus="getBuilding"
                class="handle-input mr10"
            >
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.name"
                  :value="item.name"
              >
                <span style="float: left">{{ item.name }}</span>
                <span style="
                padding-left: 50px;
                color: var(--el-text-color-secondary);
                font-size: 13px; ">{{ item.region }}</span>
                <span style="
                 padding-left: 50px;
                color: var(--el-text-color-secondary);
                font-size: 13px; "
                >{{ item.type }}</span
                >
                <!--              <span style="-->
                <!--                 padding-left: 50px;-->
                <!--                color: var(&#45;&#45;el-text-color-secondary);-->
                <!--                font-size: 13px; "-->
                <!--              >【{{ item.floor }}】层</span-->
                <!--              >-->
              </el-option>
            </el-select>
          </el-form-item>
          <!--        <el-input-->
          <!--            v-model="query.name"-->
          <!--            placeholder="楼栋名"-->
          <!--            class="handle-input mr10"-->
          <!--        ></el-input>-->
          <!--        <el-input-->
          <!--            v-model="query.type"-->
          <!--            placeholder="类型"-->
          <!--            class="handle-input mr10"-->
          <!--        ></el-input>-->
          <el-radio v-model="query.type" label="男生公寓" border> 男生公寓</el-radio>
          <el-radio v-model="query.type" label="女生公寓" border>女生公寓</el-radio>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >查询
          </el-button
          >
          <el-button @click="onReset">重置</el-button>
        </el-form>
        <el-divider/>

      </div>
      <div style="display: flex">
        <el-form :inline="true" :model="inputDate" class="demo-form-inline">
          <el-form-item label="所属校区">
            <el-input v-model="inputDate.region" disabled/>
          </el-form-item>
          <el-form-item label="公寓名称">
            <el-input v-model="inputDate.name" disabled/>
          </el-form-item>
          <el-form-item label="住宿类型">
            <el-input v-model="inputDate.type" disabled/>
          </el-form-item>
          <el-form-item label="楼层数量">
            <el-input-number v-model="inputDate.floorNum" :disabled="true"/>
          </el-form-item>
        </el-form>
      </div>

      <el-divider/>
      <div class="clits">
        <div><i class="el-icon-s-data"></i>楼层信息列表</div>
      </div>
      <el-table
          :data="childrenDte"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
      >
        <el-table-column label=" 所属楼层" prop="room" align="center">
          <template #default="scope">
            第【{{ scope.row.floor }}】层
          </template>
        </el-table-column>
        <el-table-column label=" 房间数量" prop="room" align="center">
          <template #default="scope">
            共有【{{ scope.row.room }}】间
          </template>
        </el-table-column>
        <el-table-column label="房间号" prop="room" align="center">
          <template #default="scope">
            <div v-for="item in scope.row.roomList" :key="item.sid"
                 style="display: inline;flex-direction: column;padding-right: 10px ">
              <button style="padding-right: 20px" @click="handleInsertRoom(item)">
                <img style="width: 30px; display: inline"
                     src="../../assets/img/room.png"/>
                {{ item.name }}
              </button>
            </div>
          </template>

        </el-table-column>
        <el-table-column>
          <el-table-column
              label="操作"
              width="180"
              align="center"
              fixed="right"
          >
            <template #default="scope">
              <el-button
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
              >更多操作
              </el-button>
              <el-button
                  type="text"
                  icon="el-icon-circle-plus-outline"
                  @click="handleAdd(scope.row.sid)"
              >新增房间
              </el-button>
              <!--              <el-button-->
              <!--                  type="text"-->
              <!--                  icon="el-icon-delete"-->
              <!--                  class="red"-->
              <!--                  @click="handleDelete(scope.$index, scope.row.sid)"-->
              <!--              >删除-->
              <!--              </el-button-->
              <!--              >-->
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            :currentPage="query.pageNum"
            :page-sizes="[10, 20, 40]"
            :page-size="query.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageTotal"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        >
        </el-pagination>
      </div>
    </div>
    <!--  -->
    <div>
      <el-dialog
          title="床位添加"
          v-model="importVisible"
          width="50%"
          hidden
          @close="handleSearch"
          :before-close="handleClose">
        <el-form :inline="true" :model="entity" class="demo-form-inline">
          <el-form-item label="当前房间号">
            <el-input v-model="roomName" style="
            color: #f02d2d;font-size: 30px;justify-content: center;align-items: center;font-size-adjust: initial"
                      disabled/>
          </el-form-item>
          <el-form-item label="当前房间床位数量">
            <el-input v-model="entity.bedNum" style="
            color: #f02d2d;font-size: 30px;justify-content: center;align-items: center;font-size-adjust: initial"
                      disabled/>
          </el-form-item>

          <el-form-item label="当前房间存在房间">
            <el-input v-model="entity.bedName" style="
            color: #f02d2d;font-size: 30px;justify-content: center;align-items: center;font-size-adjust: initial"
                      disabled/>
          </el-form-item>
          <el-divider></el-divider>
          <el-form-item label="房间格局状态">
            <el-upload ref="pictureUpload" action="#" list-type="picture-card"
                       :limit="1" :on-exceed="handleExceed"
                       :auto-upload="false"
                       :file-list="fileList"
                       :on-change="handleFile">
              <template #default>
                <i class="el-icon-plus"></i>

              </template>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                  <span class="el-upload-list__item-actions">
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <!--        <template #footer>-->
        <!--             <span class="dialog-footer" style="color: red;display: flex;align-items: center;justify-content: center; ">请将弹窗显示的第一个床位删除再次点新增床位-->
        <!--      </span>-->
        <!--        </template>-->
        <div>
          <el-form
              ref="dynamicValidateForm"
              :model="dynamicValidateForm"
              label-width="25%"
              class="demo-dynamic"
              :rules="rules">
            <el-form-item
                v-for="(domain, index) in dynamicValidateForm.domains"
                :key="domain.key"
                :label="'床号'"
                :prop="'domains.' + index + '.value'">
              <img style="width: 200px;height: 130px; display: inline"
                   src="../../assets/img/dchuang.png"/>
              <el-input v-model="domain.bedList.name" aria-required="true"/>
              <el-button @click.prevent="removeDomain(domain)" icon="iconfont icon-guanbi" type="text" size="small">删除
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button @click="addDomain()">新增床位</el-button>
              <!--                    <el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>-->
            </el-form-item>
            <!--            <el-button @click="addDomain()">新增床位</el-button>-->
            <!--            <div style="display: inline;float:right">-->
            <el-form-item style="display: inline;padding-right: 100px">
              <el-button type="primary" @click="submitCancel()"
              >取消
              </el-button>
              <el-button type="primary" @click="submitForm( dynamicValidateForm.domains.bedList)"
              >提交
              </el-button>
            </el-form-item>

            <!--            </div>-->
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import request from "../../utils/request";

export default {
  name: "buildingRoom",
  data() {
    return {
      dynamicValidateForm: {
        domains: [
          {
            key: 2,
            bedList: {
              name: "",
              roomId: this.roomid
            },
          },
        ],
      },
      importVisible: false,
      roomid: "",
      bedList: [],
      resbedList: [],
      entity: {
        bedNum: 0,
        bedName: "",
      },
      roomId: "",
      roomName: ""
    }

  },
  methods: {
    submitCancel() {
      this.importVisible = false
      this.formData.delete("roomId")
    },
    submitForm() {
      console.log(this.formData.get("roomId") + "____1212")
      // this.formData.append("names", null)
      this.bedList = [];
      // console.log(this.dynamicValidateForm.domains.length)
      for (var i = 0; i < this.dynamicValidateForm.domains.length; i++) {
        // if (this.dynamicValidateForm.domains[i].bedList.name == null) {
        //   ElMessage.error("当前房间号必填" + this.dynamicValidateForm.domains[i].bedList.name);
        //   return null
        // } else {
        this.bedList.push(this.dynamicValidateForm.domains[i].bedList)
        // }
      }
      console.log(this.bedList);
      for (var j = 0; j < this.bedList.length; j++) {
        this.roomId = "";
        console.log(j + this.bedList[j].name + "到位了")
        // this.formData.append("bedList",JSON.parse(JSON.stringify(this.bedList[j])))
        this.formData.append("names", this.bedList[j].name)
        this.roomId = this.bedList[j].roomId
      }
      // this.formData.append("roomId", this.roomId)
      // this.formData.append("bedList", this.bedList)
      // console.log(this.formData.get("bedList"))
      request
          .post("/bed/insertBedBatchFile",
              this.formData,
              {
                headers: {"Content-Type": "multipart/form-data"}
              }).then((res) => {
        this.bedList = []
        this.formData.delete("files")
        this.formData.delete("names")
        this.formData.delete("roomId")
        if (res.code != null) {
          ElMessage.warning(res.msg);
          this.importVisible = false
          this.dynamicValidateForm.domains = []
        } else {
          ElMessage.success("成功");
          this.importVisible = false;
          this.dynamicValidateForm.domains = []
        }
      })
    },
    // resetForm(formName) {
    //   this.$refs[formName].resetFields()
    // },
    removeDomain(item) {
      const index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    }
    ,
    addDomain() {
      this.dynamicValidateForm.domains.push({
        key: Date.now(),
        bedList: {
          name: "",
          roomId: this.roomid
        },
      })
    }
    ,
    //新增床位

    handleInsertRoom(item) {
      this.roomName = item.name
      this.formData.append("roomId", item.sid)
      this.fileList = []
      this.importVisible = true
      this.roomid = ""
      console.log(item.sid)
      this.roomid = item.sid
      this.entity.bedNum = 0
      this.entity.bedName = ""
      request.get("/bed/ByRoomId/" + item.sid).then((res) => {
        this.resbedList = res.data
        if (this.resbedList.length > 0) {
          this.entity.bedNum = this.resbedList.length
          for (var i = 0; i < this.resbedList.length; i++) {
            this.entity.bedName += this.resbedList[i].name + "号" + ";"
          }
          var file = {
            url: ""
          };
          if (this.resbedList[0].roomurl !== null && this.resbedList[0].roomurl !== "") {
            file.url = this.resbedList[0].roomurl;
            this.fileList.push(file);
          }
          console.log(this.fileList);
        }
      });
    }
    ,
    //文件上传
    //文件数量控制
    handleExceed(files, fileList) {
      console.log(fileList)
      console.log("调用我了 ")
      this.$message.warning(
          `The limit is 1, you selected ${
              files.length
          } files this time, add up to ${files.length + fileList.length} totally`
      );
    }
    ,
    //文件移除
    handleRemove(file) {
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
          this.fileList.splice(i, 1)
          console.log(this.fileList)
        }
      }
    }
  },

  setup() {
    const root = "/building/";
    const router = useRouter();
    // const importVisible = ref(false);
    const props = [
      {label: "所属楼层", prop: "floor"},
      {label: "房间数量", prop: "room"},
      // {label: "类型", prop: "type"},
      // {label: "楼号", prop: "floor"},
    ];
    const inputDate = reactive({
      name: "", //公寓名称
      type: "",//类型
      floorNum: "", //楼层数量
      region: "",
    });
    const query = reactive({
      region: "",
      name: "一公寓",
      type: "",
      pageNum: 1,
      pageSize: 10,
    });
    const tableData = ref([]);
    const childrenDte = ref([]);
    const pageTotal = ref(0);
    // 获取表格数据
    const getData = () => {
      request
          .get(root + "createBuildingRoom", {
            params: query,
          })
          .then((res) => {
            if (res.code == 18) {
              ElMessage.warning(res.msg);
              tableData.value = [];
            } else {
              inputDate.type = res.data.type;
              inputDate.region = res.data.region
              inputDate.name = res.data.name
              inputDate.floorNum = res.data.floorNum
              childrenDte.value = res.data.buildingList;

              /* for (var i = 0; i < tableData.value.length; i++) {
                 if (tableData.value[i].roomList == null) {
                   tableData.value[i].room = "--";
                 }
               }*/
              pageTotal.value = res.data.total;
            }
          });
    };
    getData();
    // 查询操作
    const handleSearch = () => {
      query.pageNum = 1;
      getData();
    };
    // 分页大小
    const handleSizeChange = (val) => {
      query.pageSize = val;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageNum = val;
      getData();
    };
    // 删除操作
    const handleDelete = (index, sid) => {
      // 二次确认删除
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
          .then(() => {
            request.delete(root + sid).then((res) => {
              if (res.data) {
                ElMessage.success("删除成功");
                tableData.value.splice(index, 1);
              } else {
                ElMessage.error("删除失败");
              }
            });
          })
          .catch(() => {
          });
    };
    // 新增操作
    const handleAdd = (sid) => {
      router.push({path: "/admin/addRoom", query: {id: sid}});
    };

    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    const handleEdit = (row) => {
      router.push({
        path: "/admin/roomEdit",
        query: {region: row.region, name: row.name, type: row.type, floor: row.floor}
      });
    };
    const onReset = () => {
      query.region = "",
          query.name = "",
          query.type = " "
    };
    //楼层
    const options = ref([]);
    const getBuilding = () => {
      request.get("/building/getAllName").then((res) => {
        options.value = res.data;
      });
    };
    //文件上传
    const disabled = ref(false)
    // const importVisible = ref(false)
    const formData = new FormData();
    const fileList = ref([]);
    const formReceive = reactive({
      goodsName: "",
      goodsId: "",
      sid: ""
    });
    // const handleEdit = (row) => {
    //   importVisible.value = true
    //   formReceive.goodsName = row.goodsName
    //   formReceive.goodsId = row.goodsId
    //   formReceive.sid = row.sid
    //   handleGetReceive(row.sid)
    // };
    // const handleGetReceive = (sid) => {
    //   fileList.value = []
    //   request.get(root + sid).then((res) => {
    //     var tadate = [];
    //     tadate = res.data.filesUrl.split(',')
    //     console.log(tadate.length)
    //     for (var i = 0; i < tadate.length; i++) {
    //       var file = {
    //         url: ""
    //       }
    //       file.url = tadate[i]
    //       if (file.url != null && file.url.length > 0) {
    //         fileList.value.push(file)
    //       }
    //     }
    //     console.log(fileList.value)
    //   });
    // };
    const handleFile = (file, fileList) => {
      console.log(fileList)
      formData.delete("files")
      for (var i = 0; i < fileList.length; i++) {
        console.log(fileList[i])
        formData.append("files", fileList[i].raw);
      }
      // console.log(formData.getAll("files"))
    };

    const handleClose = (done) => {
      ElMessageBox.confirm('确定关闭窗口吗?')
          .then(() => {
            done()
            this.formData.delete("roomId")
          })
          .catch(() => {
            // catch error
          })
    }
    return {
      props,
      query,
      tableData,
      pageTotal,
      editVisible,
      childrenDte,
      options,
      getBuilding,
      // importVisible,
      // form,
      disabled,
      formData,
      fileList,
      inputDate,
      // dynamicValidateForm,
      // removeDomain,
      // addDomain,
      onReset,
      handleSearch,
      handleSizeChange,
      handlePageChange,
      handleAdd,
      handleDelete,
      handleEdit, handleFile, handleClose,
      // handleGetReceive,
      // handleInsertRoom,
    };
  },
};
</script>

<style scoped>
.clits {
  background: #3ca2e0;
  height: 50px;
  font-size: 25px;
  display: flex;
  align-items: center;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
